﻿using NHibernate.Criterion;
using Online_Course.Core;
using Online_Course.Domain;
using Online_Course.Service;
using Online_Course.Web.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Online_Course.Web.Controllers
{
    public class SysUserController : Controller
    {
        //
        // GET: /SysUser/
        #region 列表
        public ActionResult Index(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件的记录
            int count = 0;
            IList<Order> listOrder = new List<Order>() { new Order("ID", true) };
            IList<SysUser> list = Container.Instance.Resolve<ISysUserService>().Query(new List<ICriterion>() { new LikeExpression("Name", "%" + qryUserName + "%") }, listOrder, pageIndex, PagerHelper.PageSize, out count);
            //转换为PageList集合
            PageList<SysUser> pageList = list.ToPageList<SysUser>(
                pageIndex,
                PagerHelper.PageSize,
                count);
            return View(pageList);//用pageList集合填充页面。
        }
        #endregion

        #region 登录
        public ViewResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="account">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>是否成功；0用户名密码错误</returns>
        [HttpPost]
        public string login(string account, string password = "", string txtValidate = "")
        {
            if (Session["CheckCode"] != null)
            {
                string checkcode = Session["CheckCode"].ToString();
                if (txtValidate.Trim() == checkcode)
                {

                    IList<ICriterion> listQuery = new List<ICriterion>() 
                    { Expression.Eq("Account", account), 
                      Expression.Eq("Password", AppHelper.EncodeMd5(password)),
                      Expression.Eq("IsActive",1) };
                    SysUser loginUser = Container.Instance.Resolve<ISysUserService>().Query(listQuery).FirstOrDefault();
                    if (loginUser != null)
                    {
                        AppHelper.LoginedUser = loginUser;//保存用户登录信息
                        return "登录成功！";//将要跳转的页面路径返回视图http://localhost:2533/User/LoginIndex
                    }
                    return "0";//代表用户户或密码错误
                }
                else
                {
                    return "1";//验证码错误
                }
            }
            else
            {
                return "0";//代表用户户或密码错误
            }
        }
        #endregion

        #region 注册
        public ActionResult register()
        {
            return View();
        }

        [HttpPost]
        public string Register(SysUser user, Student student, string username, string stucode, string password, string confirm_password, string number)
        {
            //用户名和密码均不为空
            if (username != null && password != null)
            {
                //密码与确认密码不相等
                if (password != confirm_password)
                {
                    return "1";
                }
                else
                    //用户名密码或学号长度<3
                    if (username.Length < 2 || stucode.Length < 2 || username.Length < 2)
                    {
                        return "0";
                    }
                    else
                    {
                        //构造用户和学生实体
                        user.Name = username;
                        user.Account = stucode;
                        user.Password = AppHelper.EncodeMd5(password);
                        user.Phone = number;
                        user.SysRoleList = Container.Instance.Resolve<ISysRoleService>().Query(new List<ICriterion>() { Expression.In("ID", new int[] { 2 }) });
                        user.IsActive = 1;
                        student.Name = username;
                        student.Phone = number;
                        student.IsActive = 1;
                        student.Code = stucode;
                        //将数据保存到数据库中
                        Container.Instance.Resolve<ISysUserService>().Add(user);
                        Container.Instance.Resolve<IStudentService>().Add(student);
                    }
            }
            else
            {
                return "false";
            }
            return "true";
        }

        #endregion


        #region 密码修改
        public ActionResult Modify()
        {
            return View();
        }

        [HttpPost]
        public string Modify(string username, string password, string confirm_password, string txtValidate = "")
        {
            //获取当前登录用户的信息
            int Userid = AppHelper.LoginedUser.ID;
            SysUser User = Container.Instance.Resolve<ISysUserService>().GetEntity(Userid);
            if (Session["CheckCode"] != null)
            {
                if (password == confirm_password)
                {
                    string checkcode = Session["CheckCode"].ToString();
                    if (txtValidate.Trim() == checkcode)
                    {
                        //修改密码保存到数据库
                        User.Account = username;
                        User.Password = AppHelper.EncodeMd5(password);
                        Container.Instance.Resolve<ISysUserService>().Update(User);
                    }
                    else
                    {
                        return "0";//验证码错误
                    }

                }
                else
                {
                    return "1";
                }
            }
            return "修改成功！";
        }
        #endregion

        #region 新增
        public ActionResult Create()
        {
            SysUser user = new SysUser();
            //获取所有角色
            IList<SysRole> lst = Container.Instance.Resolve<ISysRoleService>().GetAll();
            IList<SelectListItem> lstRole = new List<SelectListItem>();
            //构建角色多选框的内容；
            foreach (var r in lst)
            {
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = false };
                lstRole.Add(sli);
            }
            ViewBag.lstRole = lstRole;
            //构建状态信息
            IList<SelectListItem> lstStatus = new List<SelectListItem>() 
            { 
                 new SelectListItem(){Value="1",Text="激活",Selected=true},
                 new SelectListItem(){Value="2",Text="禁用",Selected=false}
            };
            ViewBag.lstStatus = lstStatus;
            return View(user);

        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <param name="roleIDs">角色IDS</param>
        /// <param name="statusValue">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SysUser user, string roleIDs = "", string statusValue = "0")
        {
            try
            {
                //拆分角色字符串；
                string[] arrIds = roleIDs.Split(',');
                IList<SysRole> roleList = new List<SysRole>();
                Student stu = new Student();
                Teacher tea = new Teacher();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //根据ID查找角色信息
                        roleList.Add(Container.Instance.Resolve<ISysRoleService>().GetEntity(Int32.Parse(n)));
                        if (n == "2")
                        {
                            stu.Phone = user.Phone;
                            stu.Code = user.Account;
                            stu.Name = user.Name;
                            stu.IsActive = 1;
                            //保存到数据库中
                            Container.Instance.Resolve<IStudentService>().Add(stu);
                        }
                        if (n == "3")
                        {
                            tea.Name = user.Name;
                            tea.Phone = user.Phone;
                            tea.TeacherCode = user.Account;
                            tea.IsActive = 1;
                            //保存到数据库中
                            Container.Instance.Resolve<ITeacherService>().Add(tea);
                        }
                    }
                }
                //构建实体
                user.SysRoleList = roleList;
                user.Password = AppHelper.EncodeMd5(user.Password);
                user.IsActive = Int32.Parse(statusValue);
                //保存到数据库中
                Container.Instance.Resolve<ISysUserService>().Add(user);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            //根据ID 查询要修改的实体
            SysUser entity = Container.Instance.Resolve<ISysUserService>().GetEntity(id);
            //查询所有角色信息；
            IList<SysRole> roleList = Container.Instance.Resolve<ISysRoleService>().GetAll();
            //构建角色多选框，标记哪些角色被选中
            IList<SelectListItem> sliRole = new List<SelectListItem>();
            foreach (SysRole r in roleList)
            {
                bool isExist = false;
                //查找是否存在该用户的角色列表中；
                int count = entity.SysRoleList.Where(o => o.ID == r.ID).Count();
                //如果>0，则要被选中，否则不勾选；
                if (count > 0)
                { isExist = true; }
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = isExist };
                sliRole.Add(sli);
            }
            ViewBag.RoleList = sliRole;

            //构建状态，并标记是否被选中；
            IList<SelectListItem> lstIsActive = new List<SelectListItem>();
            SelectListItem itm = new SelectListItem() { Value = "1", Text = "激活", Selected = false };
            if (entity.IsActive.Equals(1))
            {
                itm.Selected = true;
            }
            lstIsActive.Add(itm);
            itm = new SelectListItem() { Value = "0", Text = "禁用", Selected = false };
            if (entity.IsActive.Equals(0))
            {
                itm.Selected = true;
            }

            lstIsActive.Add(itm);
            ViewBag.lstIsActive = lstIsActive;
            return View(entity);
        }

        [HttpPost]
        public ActionResult Edit(int id, SysUser entity, string roleIDs = "", string statusValue = "0")
        {

            //根据ID获取需要修改的用户；
            SysUser user = Container.Instance.Resolve<ISysUserService>().GetEntity(id);
            try
            {
                string[] arrIds = roleIDs.Split(',');
                IList<SysRole> roleList = new List<SysRole>();
                Student stu = new Student();
                Teacher tea = new Teacher();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //查询当前ID的角色，并添加到角色列表中
                        roleList.Add(Container.Instance.Resolve<ISysRoleService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建用户实体
                user.SysRoleList = roleList;
                //user.Password = AppHelper.EncodeMd5(user.Password);
                user.IsActive = Int32.Parse(statusValue);
                user.Name = entity.Name;
                user.Account = entity.Account;
                if (entity.Name != null && entity.Password != "")
                {
                    user.Password = AppHelper.EncodeMd5(entity.Password);
                }
                //修改实体，保存
                Container.Instance.Resolve<ISysUserService>().Update(user);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 操作
        public ActionResult SwitchStatus(int id, string type)
        {
            SysUser user = Container.Instance.Resolve<ISysUserService>().GetEntity(id);
            if (type.Equals("Active"))
            {
                user.IsActive = 1;
            }
            else if (type.Equals("Enabled"))
            {
                user.IsActive = 0;
            }
            Container.Instance.Resolve<ISysUserService>().Update(user);
            return RedirectToAction("Index");//跳转到列表页面
        }
        public ActionResult Delete(int id, string type)
        {
            SysUser User = Container.Instance.Resolve<ISysUserService>().GetEntity(id);
            Container.Instance.Resolve<ISysUserService>().Delete(User);
            return RedirectToAction("Index");//跳转到列表页面
        }

        #endregion
    }
}
